package org.jeecg.modules.system.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.constant.ErrorMsg;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.MD5Utils;
import org.jeecg.config.Sm4Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Slf4j
public class RestTemplateUtil {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RestTemplate restTemplate;
//    private static  final String key = "04720B3F2FAD4612B5A9FEFF7B20ADA9";
    private static  final String key = "5F71191D102F2292DF9E11D8BA35BBB0";


    public JSONObject postForEntity(Map<String,Object> map, String url, Map<String,Object> uriVariables) {
        if(uriVariables == null){
            uriVariables = new HashMap<>();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String value = null;
        try {
            value = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        log.info("postForEntity接口请求地址:{},请求参数:{}",url,value);
        HttpEntity<String> request = new HttpEntity<>(value, headers);
        ResponseEntity<String> result =  restTemplate.postForEntity(url,request, String.class,uriVariables);
        if(result.getBody() == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        String bodyString = result.getBody();
        JSONObject returnJSON = JSONObject.parseObject(bodyString);
        if(returnJSON == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        log.info("postForEntity接口返回数据:{}",bodyString);
        return returnJSON;
    }

    /**
     * 对接上海市公共停车平台使用
     * @param map
     * @param url
     * @param secretKey
     * @return
     */
    public JSONObject postForEntitySecret(Map<String,Object> map, String url,String secretKey) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Accept",MediaType.APPLICATION_JSON_VALUE);
        String value = null;
        try {
            value = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            new JeecgBootException(500,e.getMessage());
        }
        String signInput = secretKey + "|" + value;
//        log.info("signInput:{}",signInput);
        String sign = MD5Utils.getMd5(signInput);
        headers.add("sign",sign.toLowerCase());
        HttpEntity<String> request = new HttpEntity<>(value, headers);
        log.info("postForEntity接口请求地址:{},请求参数:{},head部:{}",url,value,headers);
        ResponseEntity<String> result =  restTemplate.postForEntity(url,request, String.class);
        if(result.getBody() == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        String bodyString = result.getBody();
        JSONObject returnJSON = JSONObject.parseObject(bodyString);
        if(returnJSON == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        log.info("postForEntity接口返回数据:{}",bodyString);
        return returnJSON;
    }


    public JSONObject postForEntityJson(String jsonParam, String url, Map<String,Object> uriVariables) {
        if(uriVariables == null){
            uriVariables = new HashMap<>();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        log.info("postForEntity接口请求地址:{},请求参数:{}",url,jsonParam);
        HttpEntity<String> request = new HttpEntity<>(jsonParam, headers);
        ResponseEntity<String> result =  restTemplate.postForEntity(url,request, String.class,uriVariables);
        if(result.getBody() == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        String bodyString = result.getBody();
        JSONObject returnJSON = JSONObject.parseObject(bodyString);
        if(returnJSON == null){
            throw new JeecgBootException(ErrorMsg.RETUAN_DATA_IS_NULL);
        }
        log.info("postForEntity接口返回数据:{}",bodyString);
        return returnJSON;
    }

    public static JSONObject doPost(String url, String json) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        String cipher = Sm4Util.encryptEcb(key, json);
        log.info("请求数据:{}",cipher);
        StringEntity s = new StringEntity(cipher);
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String result = EntityUtils.toString(res.getEntity());// 返回json格式：
            cipher = Sm4Util.decryptEcb(key, result);
            response = JSONObject.parseObject(cipher);
        }
        return response;
    }
}
